<?php

/**
 * Form input that uses radio buttons to display data
 *
 * @author shenlon
 */
class FormRadioInput extends FormInput {

    /**
     * Array of data
     * @var Array
     */
    private $data;

    /**
     * Checked element
     * @var String
     */
    private $checked;

    /**
     * Default constructor
     * @param String $name
     * @param String $required
     * @param Array $data
     * @param Array $options 
     */
    public function __construct($name, $required, $data, $options = null) {
        parent::__construct($name, $required);
        $this->data = $data;
        if ($options != null)
            foreach ($options as $key => $value) {
                if (property_exists($this, $key))
                    $this->$key = $value;
                else
                    $this->optionalData[$key] = $value;
            }
    }

    /**
     * Renders form input by using radio buttons
     * @return string 
     */
    public function renderFormInput() {
        $html = '';
        if ($this->label != '')
            $html = "<label for='{$this->name}'>{$this->label}</label>\n";
        foreach ($this->data as $key => $value) {
            $checked = ($this->checked == $key) ? 'checked' : '';
            $ahtml = '<input type="radio" name="' . $this->name . '" value="' . $key . '" ' . $checked . '>' . $value . "<br/>\n";
            if ($this->container != '')
                $html .= sprintf($this->container, $ahtml);
            else
                $html .= $ahtml;
        }
        if (count($this->optionalData) > 0) {
            //foreach ($this->optionalData as $key => $value)
            //    $html .= "$key = '$value' ";
        }
        return $html;
    }

    /**
     * Validates data by calling FormInput->validateData and by checking if the value passed exists in input data
     * @param Object $data
     * @return Array 
     */
    public function validateData($data) {
        $errorMsg = "Wartość $data nie jest poprawną wartością.";
        $errors = parent::validateData($data);
        if (!in_array($data, $this->data)) {
            if (!is_array($errors))
                $errors = array($errorMsg);
            else
                $errors[] = $errorMsg;
        }
        return $errors;
    }

}

?>
